//******************************************************************
//******************************************************************
//**********          ANts Peer To Peer Sources        *************
//
// ANts P2P realizes a third generation P2P net. It protects your
// privacy while you are connected and makes you not trackable, hiding
// your identity (ip) and crypting everything you are sending/receiving
// from others.

// Copyright (C) 2004  Roberto Rossi

// This program is free software; you can redistribute it and/or
// modify it under the terms of the GNU General Public License
// as published by the Free Software Foundation; either version 2
// of the License, or (at your option) any later version.

// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.

// You should have received a copy of the GNU General Public License
// along with this program; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.

package ants.p2p.query.security;

import java.security.*;
import javax.crypto.spec.*;
import javax.crypto.*;
import java.io.*;

import ants.p2p.utils.encoding.*;

import org.apache.log4j.*;

public class SimmetricProvider {
  public static final String cipher = "AES";
  public static final int cipherKeySize = 16;

  static Logger _logger = Logger.getLogger(SimmetricProvider.class.getName());

  public SimmetricProvider() {
  }

  public static byte[] encrypt(String sessionKey, byte[] message) {
    try {
      SecretKeySpec skeySpec = new SecretKeySpec(Base16.fromHexString(sessionKey),
                                                 SimmetricProvider.cipher);
      Cipher cipher = Cipher.getInstance(SimmetricProvider.cipher);

      cipher.init(Cipher.ENCRYPT_MODE, skeySpec);
      byte[] encrypted = cipher.doFinal(message);
      return encrypted;
    }
    catch (Exception e) {
      _logger.error("",e);
    }
    return null;
  }

  public static byte[] decrypt(String sessionKey, byte[] message) {
    try {
      SecretKeySpec skeySpec = new SecretKeySpec(Base16.fromHexString(sessionKey),
                                                 SimmetricProvider.cipher);
      Cipher cipher = Cipher.getInstance(SimmetricProvider.cipher);

      cipher.init(Cipher.DECRYPT_MODE, skeySpec);
      byte[] original = cipher.doFinal(message);
      return original;
    }
    catch (Exception e) {
      _logger.error("",e);
    }
    return null;
  }
}

